﻿'    Open Subtitle Editor
'    Copyright (c) 2009-2010 Discovery OSS Team
'
'    This file is part of Open Subtitle Editor.
'
'    Open Subtitle Editor is free software: you can redistribute it and/or modify
'    it under the terms of the GNU General Public License as published by
'    the Free Software Foundation, either version 3 of the License, or
'    (at your option) any later version.
'
'    Open Subtitle Editor is distributed in the hope that it will be useful,
'    but WITHOUT ANY WARRANTY; without even the implied warranty of
'    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
'    GNU General Public License for more details.
'
'    You should have received a copy of the GNU General Public License
'    along with Open Subtitle Editor.  If not, see <http://www.gnu.org/licenses/>.

Imports System.Reflection

Public Class frmMain

    Public subsFileReader As System.IO.StreamReader

    Public VersionComment As String = "beta"

    Public delayBefore As Integer
    Public delayAfter As Integer
    Public stopOnEndOfSub As Boolean
    Public commonDelay As Integer

    'Row number for the subtitle matching the current video time
    Public currentRow As Integer
    Public currentFPS As Double = 0
    Public tick As Short
    Private readyStatusString As String
    Public cursub(3) As String
    Public stopDblClickPrevTime As Integer
    Public oldRow As Integer = -1
    Private wasPaused As Boolean
    Private tempSub As New Subtitles.SubtitleType
    Private editMode As Boolean = False

    Public mySubtitles As New Subtitles

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        If AlreadyRunning() = True Then
            MsgBox(loadStringFromLangFile("alreadyRunningOSE"), MsgBoxStyle.Exclamation)
            End
        End If

        Dim myImages As New ImageList()
        myImages.Images.Add("information", System.Drawing.SystemIcons.Information)
        tabControl.ImageList = myImages

        If My.Computer.Registry.GetValue(AppRegKey, "NotFirstRun", Nothing) Is Nothing Then
            Dim temp As String = "Open Subtitle Editor has a video preview feature which uses Windows Media " & _
                                 "Player technology. That means that any video that the Windows Media Player " & _
                                 "that is currently installed on your computer can play, Open Subtitle Editor " & _
                                 "can play as well." & newLine & newLine & _
                                 "However, if you receive an error while trying to play a video file or " & _
                                 "only hear sound and see no video playing, then it's quite probable that " & _
                                 "you're missing a required codec." & newLine & newLine & _
                                 "See warning.txt for more information. It's located in the folder that Open " & _
                                 "Subtitle Editor was installed (by default, C:\Program Files\Open Subtitle Editor)."
            MsgBox(temp, MsgBoxStyle.Information)

            ' Remove old Open Subtitle Editor registry entries.
            Dim tempReg As Microsoft.Win32.RegistryKey = Microsoft.Win32.Registry.CurrentUser
            tempReg.DeleteSubKeyTree("Software\Discovery Open-Source Development Group\" & Application.ProductName)

            My.Computer.Registry.SetValue(AppRegKey, "NotFirstRun", 1)
        End If

        lblShowSub.Left = mPlayer.Left
        Me.Text = Application.ProductName & " " & VersionNumberInterpretation()
        addToDebugList(Application.ProductName & " " & VersionNumberInterpretation())

        ' Get language file setting from registry and load it.
        If My.Computer.Registry.GetValue(AppRegKey, "LanguageFile", Nothing) Is Nothing Then
            loadTranslation(2)
        Else
            loadTranslation(1)
        End If

        nudShow.Accelerations.Add(New NumericUpDownAcceleration(2, 100))
        nudShow.Accelerations.Add(New NumericUpDownAcceleration(5, 500))
        nudShow.Accelerations.Add(New NumericUpDownAcceleration(8, 1000))
        nudShow.Accelerations.Add(New NumericUpDownAcceleration(11, 5000))

        nudHide.Accelerations.Add(New NumericUpDownAcceleration(2, 100))
        nudHide.Accelerations.Add(New NumericUpDownAcceleration(5, 500))
        nudHide.Accelerations.Add(New NumericUpDownAcceleration(8, 1000))
        nudHide.Accelerations.Add(New NumericUpDownAcceleration(11, 5000))

        mPlayer.uiMode = "none"
        mPlayer.Ctlenabled = False
        mPlayer.enableContextMenu = False
        mPlayer.settings.volume = sldVolume.Value

        rtbSubtitle.Left = chkBold.Right + 10

        rtbSubtitle.SelectionAlignment = HorizontalAlignment.Center

        cmbFRorFFby.SelectedIndex = 2
        toolTip.SetToolTip(sldVolume, sldVolume.Value)
        ViewTabsToolStripMenuItem_Click(Nothing, Nothing)

        LoadSettings()
        ParseKnownLanguageFiles()


    End Sub

    Private Sub dgvSubtitles_CellEndEdit(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgvSubtitles.CellEndEdit
        If e.ColumnIndex = 1 Or e.ColumnIndex = 2 Then
            If Not getFirstDebugListItem() = loadStringFromLangFile("pleaseCheckForOverlaps") Then
                addToDebugList(loadStringFromLangFile("pleaseCheckForOverlaps"))
            End If
        End If

        Select Case e.ColumnIndex
            Case 1
                mySubtitles.setShowTime(e.RowIndex, dgvSubtitles.Rows(e.RowIndex).Cells(e.ColumnIndex).Value)
            Case 2
                mySubtitles.setHideTime(e.RowIndex, dgvSubtitles.Rows(e.RowIndex).Cells(e.ColumnIndex).Value)
            Case 3
                mySubtitles.setText(e.RowIndex, dgvSubtitles.Rows(e.RowIndex).Cells(e.ColumnIndex).Value)
        End Select

    End Sub

    Private Sub dgvSubtitles_RowHeaderMouseClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellMouseEventArgs) Handles dgvSubtitles.RowHeaderMouseClick
        Try
            If TimerSub.Enabled = True Then
                mPlayer.Ctlcontrols.currentPosition = (mySubtitles.getShowTimeInMS(e.RowIndex) + commonDelay) / 1000
                updateCurrentPositionLabel()
                playMovie()
            End If
        Catch
            addToDebugList(loadStringFromLangFile("unableToMoveToSelectedSub") & " (" & e.RowIndex & ")")
            ViewTabsToolStripMenuItem.Checked = True
            tabControl.SelectedTab = tabDebug
            ViewTabsToolStripMenuItem_Click(Nothing, Nothing)
        End Try

    End Sub

    Private Sub StartMovieOnStartSubtitle(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellMouseEventArgs) Handles dgvSubtitles.RowHeaderMouseDoubleClick
        If mPlayer.URL = "" Then Exit Sub

        Dim toEdit(3) As String
        Dim subSeconds As Double
        Dim cursub(2) As String


        Try
            oldRow = -1
            TimerSub.Enabled = False


            subSeconds = (mySubtitles.getShowTimeInMS(e.RowIndex) - delayBefore + commonDelay) / 1000
            stopDblClickPrevTime = mySubtitles.getHideTimeInMS(e.RowIndex)

            mPlayer.Ctlcontrols.currentPosition = subSeconds

            mPlayer.Ctlcontrols.play()
            findSubForCurrentTime()

            Timer.Enabled = True
        Catch
            addToDebugList(loadStringFromLangFile("unableToMoveToSelectedSub") & " (" & e.RowIndex & ")")
            ViewTabsToolStripMenuItem.Checked = True
            tabControl.SelectedTab = tabDebug
            ViewTabsToolStripMenuItem_Click(Nothing, Nothing)
        End Try


    End Sub

    Private Sub CheckIfMovieShouldStop(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer.Tick
        Dim subSeconds As Double
        Dim curpos(2) As String

        pnlTimerOnly.Enabled = True

        findSubForCurrentTime()

        subSeconds = (stopDblClickPrevTime + delayAfter + commonDelay) / 1000

        If mPlayer.Ctlcontrols.currentPosition > subSeconds Then
            mPlayer.Ctlcontrols.pause()
        End If
    End Sub

    Private Sub ExitToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExitToolStripMenuItem.Click
        Application.Exit()
    End Sub

    Public Sub LoadLangStrings()

        'langFileReader = My.Computer.FileSystem.OpenTextFileReader(My.Computer.Registry.GetValue(AppRegKey, "LanguageFile", Nothing))

        'While Not langFileReader.EndOfStream
        '    Dim line As String = langFileReader.ReadLine
        '    If Not (line = "" Or Microsoft.VisualBasic.Left(line, 1) = ("!"c)) Then
        '        Dim splitLine As String() = line.Split(New Char() {","c}, 2)
        '        Dim controlName As String = splitLine(0)
        '        Dim controlText As String = LTrim(splitLine(1))

        '        Dim a As Object = Me.GetType().GetField(controlName, BindingFlags.NonPublic Or BindingFlags.Instance Or BindingFlags.Static).GetValue(Me)
        '        a.Text = "Hello"

        '        'Dim controlField As FieldInfo = Me.GetType().GetField(controlName, BindingFlags.NonPublic Or BindingFlags.Instance Or BindingFlags.Static)
        '        'Dim textProperty As PropertyInfo = controlField.GetType().GetProperty("Text")
        '    End If

        'End While

        readyStatusString = loadStringFromLangFile("readyStatus")
        SubtitleToolStripMenuItem.Text = loadStringFromLangFile("subtitleMenu")
        OpenToolStripMenuItem.Text = loadStringFromLangFile("openMenuItem")
        SaveToolStripMenuItem.Text = loadStringFromLangFile("saveMenuItem")
        ExitToolStripMenuItem.Text = loadStringFromLangFile("exitMenuItem")
        MovieToolStripMenuItem.Text = loadStringFromLangFile("movieMenu")
        EditToolStripMenuItem.Text = loadStringFromLangFile("preferencesMenu")
        LanguageToolStripMenuItem.Text = loadStringFromLangFile("languageMenu")
        LoadTranslationToolStripMenuItem.Text = loadStringFromLangFile("loadTranslationMenuItem")
        PreviewSettingsToolStripMenuItem.Text = loadStringFromLangFile("previewSettingsMenuItem")
        MovieOpenToolStripMenuItem.Text = loadStringFromLangFile("openMenuItem")
        PlayToolStripMenuItem.Text = loadStringFromLangFile("play/pauseMenu")
        ForwardToolStripMenuItem.Text = loadStringFromLangFile("forwardMenu")
        RewindToolStripMenuItem.Text = loadStringFromLangFile("rewindMenu")
        VolumeToolStripMenuItem.Text = loadStringFromLangFile("volumeText")
        volumeUpToolStripMenuItem.Text = loadStringFromLangFile("upWord")
        volumeDownToolStripMenuItem.Text = loadStringFromLangFile("downWord")
        MuteToolStripMenuItem.Text = loadStringFromLangFile("muteMenu")
        MaxToolStripMenuItem.Text = loadStringFromLangFile("maxMenu")
        PlayRateToolStripMenuItem.Text = loadStringFromLangFile("playRate")
        playRateUpToolStripMenuItem.Text = loadStringFromLangFile("upWord")
        playRateDownToolStripMenuItem.Text = loadStringFromLangFile("downWord")
        ResetToolStripMenuItem.Text = loadStringFromLangFile("resetMenu")
        EditToolStripMenuItem1.Text = loadStringFromLangFile("editMenu")
        AddToolStripMenuItem.Text = loadStringFromLangFile("addMenu")
        OnCurrentMoviePositionToolStripMenuItem.Text = loadStringFromLangFile("onCurrentMoviePositionMenu")
        StartSelectedOnCurrentPositionToolStripMenuItem.Text = loadStringFromLangFile("startSelectedHere")
        EndSelectedOnCurrentPositionToolStripMenuItem.Text = loadStringFromLangFile("endSelectedHere")
        DelayToolStripMenuItem.Text = loadStringFromLangFile("delayMenu")
        ApplyCurrentConstantDelayToolStripMenuItem.Text = loadStringFromLangFile("applyConstantDelayMenu")
        ApplyCustomDelayToolStripMenuItem.Text = loadStringFromLangFile("applyCustomDelayMenu")
        FPSConversionToolStripMenuItem.Text = loadStringFromLangFile("fpsConversionMenu")
        SetCurrentFPSToolStripMenuItem.Text = loadStringFromLangFile("setCurrentFPSMenu")
        ConvertToToolStripMenuItem.Text = loadStringFromLangFile("convertToMenu")
        CurFPS23976ToolStripMenuItem.Text = "23" & DecimalSeparator & "976"
        ToFPS23976ToolStripMenuItem.Text = CurFPS23976ToolStripMenuItem.Text
        dgvSubtitles.Columns.Item("subShow").HeaderText = loadStringFromLangFile("showTableHeader")
        dgvSubtitles.Columns.Item("subHide").HeaderText = loadStringFromLangFile("hideTableHeader")
        dgvSubtitles.Columns.Item("subText").HeaderText = loadStringFromLangFile("subtitleTableHeader")
        dgvSubtitles.Columns.Item("subProperties").HeaderText = loadStringFromLangFile("propertiesTableHeader")
        NewToolStripMenuItem.Text = loadStringFromLangFile("newMenu")
        PALNTSCFormatsToolStripMenuItem.Text = loadStringFromLangFile("pal/ntscFormats")
        PALNTSCFormatsToolStripMenuItem1.Text = PALNTSCFormatsToolStripMenuItem.Text
        ComputerUsedToolStripMenuItem.Text = loadStringFromLangFile("otherFPS")
        ComputerUsedToolStripMenuItem1.Text = ComputerUsedToolStripMenuItem.Text
        CheckForOverlappingSubtitlesToolStripMenuItem.Text = loadStringFromLangFile("checkForOverlapsMenu")
        AboutToolStripMenuItem.Text = loadStringFromLangFile("AboutToolStripMenuItem")
        HelpToolStripMenuItem.Text = loadStringFromLangFile("helpMenu")
        lblShow.Text = loadStringFromLangFile("showTableHeader") & ":"
        lblHide.Text = loadStringFromLangFile("hideTableHeader") & ":"
        tabSubPrev.Text = loadStringFromLangFile("previewTab")
        lblDuration.Text = loadStringFromLangFile("durationWord") & ":"
        SortSubtitlesBasedOnShowTimingToolStripMenuItem.Text = loadStringFromLangFile("sortSubsMenuItem")
        grpStatus.Text = loadStringFromLangFile("currentStatus")
        lblConstantDelayLabel.Text = loadStringFromLangFile("constantDelayLabel")
        lblEndAfterLabel.Text = loadStringFromLangFile("endAfterLabel")
        lblStartBeforeLabel.Text = loadStringFromLangFile("startBeforeLabel")
        Dim secondsText As String = loadStringFromLangFile("secondsText")
        Dim minutesText As String = loadStringFromLangFile("minutesText")
        toolTip.SetToolTip(cmbFRorFFby, loadStringFromLangFile("setTimeToFForFRby") & newLine & newLine & _
                        "10 = 0" & DecimalSeparator & "01 " & secondsText & newLine & _
                        "100 = 0" & DecimalSeparator & "1 " & secondsText & newLine & _
                        "1000 = 1 " & secondsText & newLine & _
                        "10000 = 10 " & secondsText & newLine & _
                        "60000 = 1 " & minutesText & newLine & _
                        "120000 = 2 " & minutesText & newLine & _
                        "600000 = 10 " & minutesText)
        lblVolume.Text = loadStringFromLangFile("volumeText")
        lblPlayRateLabel.Text = loadStringFromLangFile("playRate")
        CopyToClipboardToolStripMenuItem.Text = loadStringFromLangFile("copyToClipboard")
        tabDebug.Text = loadStringFromLangFile("debug")
        ViewTabsToolStripMenuItem.Text = loadStringFromLangFile("viewTabsMenuItem")
        btnQuickAdd.Text = loadStringFromLangFile("btnQuickAdd")
        btnQuickEdit.Text = loadStringFromLangFile("btnQuickEdit")
        chkPauseAfterQuick.Text = loadStringFromLangFile("chkPauseAfterQuick")
        toolTip.SetToolTip(btnQuickAdd, loadStringFromLangFile("quickAddToolTip"))
        toolTip.SetToolTip(btnQuickEdit, loadStringFromLangFile("quickAddToolTip"))

    End Sub

    Private Sub EnglishToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles EnglishToolStripMenuItem.Click

        loadTranslation(2)

    End Sub

    Private Sub LoadTranslationToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LoadTranslationToolStripMenuItem.Click
        loadTranslation(0)
    End Sub

    Private Sub OpenToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OpenToolStripMenuItem.Click
        If subtitleFileSaved() Then
            mySubtitles.open()
        Else
            Dim response As MsgBoxResult = MsgBox(loadStringFromLangFile("tableNotEmptyPrompt"), MsgBoxStyle.Question + MsgBoxStyle.YesNoCancel)
            Select Case response
                Case vbYes
                    mySubtitles.save()
                    mySubtitles.open()
                Case vbNo
                    mySubtitles.open()
                Case vbCancel
                    Exit Sub
            End Select
        End If

    End Sub

    Private Sub MovieOpenToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MovieOpenToolStripMenuItem.Click
        openMovie()
        playMovie()
        ViewTabsToolStripMenuItem.Checked = True
        ViewTabsToolStripMenuItem_Click(Nothing, Nothing)
    End Sub

    Private Sub TimerSub_Tick(ByVal sender As Object, ByVal e As System.EventArgs) Handles TimerSub.Tick
        Dim cursub(3) As String
        Dim CDelayInMS As Double = commonDelay / 1000

        pnlTimerOnly.Enabled = False

        updateCurrentPositionLabel()

        If dgvSubtitles.Rows.Count = 0 Then Exit Sub

        findSubForCurrentTime()

    End Sub

    Private Sub showSubForCurrentRow()

        If currentRow = -1 Then Exit Sub

        cursub = convertMultiLineTextToArray(mySubtitles.getText(currentRow))

        lblShowSub.Text = ""

        formatSubtitle()

        lblShowSub.Visible = True
        For i = 0 To cursub.Length - 1
            If Not i = cursub.Length - 1 Then
                lblShowSub.Text = lblShowSub.Text + cursub(i) + newLine
            Else
                lblShowSub.Text = lblShowSub.Text + cursub(i)
            End If
        Next

        If editMode = False Then
            If dgvSubtitles.MultiSelect = True Then
                For Each row As DataGridViewRow In dgvSubtitles.Rows
                    row.Selected = False
                Next
            End If
            dgvSubtitles.Rows(currentRow).Selected = True
            scrollToSelectedRow()
            dgvSubtitles_SelectionChanged(Nothing, Nothing)
        End If

    End Sub

    Public Sub findSubForCurrentTime()
        Dim curPosTemp As String
        Dim subStartTemp(3) As String
        Dim subStartTempSec(2) As String
        Dim subSeconds(1) As Double
        Dim foundSub As Boolean

        'Try
        foundSub = False

        curPosTemp = mPlayer.Ctlcontrols.currentPosition

        For i = 0 To dgvSubtitles.RowCount - 1
            subStartTemp = Split(dgvSubtitles.Rows(i).Cells.Item(1).Value, ":")
            subStartTempSec = Split(subStartTemp(2), ",")
            subSeconds(0) = subStartTemp(0) * 3600 & subStartTemp(1) * 60 + subStartTempSec(0) + (CDbl(subStartTempSec(1)) / 1000) + (CDbl(commonDelay / 1000))
            subStartTemp = Split(dgvSubtitles.Rows(i).Cells.Item(2).Value, ":")
            subStartTempSec = Split(subStartTemp(2), ",")
            subSeconds(1) = subStartTemp(0) * 3600 & subStartTemp(1) * 60 + subStartTempSec(0) + (CDbl(subStartTempSec(1)) / 1000) + (CDbl(commonDelay / 1000))
            If (i = 0 And subSeconds(0) > mPlayer.Ctlcontrols.currentPosition) Then
                currentRow = -1
                Exit Sub
            End If
            If subSeconds(1) > mPlayer.Ctlcontrols.currentPosition And subSeconds(0) < mPlayer.Ctlcontrols.currentPosition Then
                currentRow = i

                If oldRow = currentRow Then Exit Sub

                foundSub = True
                oldRow = i
                Exit For
            End If
        Next

        If foundSub = True Then
            lblShowSub.Visible = True
            showSubForCurrentRow()
        Else
            lblShowSub.Text = ""
            lblShowSub.Visible = False
            'dgvSubtitles.ClearSelection()
        End If
        'Catch

        'End Try
    End Sub

    Private Sub PreviewSettingsToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PreviewSettingsToolStripMenuItem.Click
        PauseMovieAndAllTimers()
        frmPreviewSettings.ShowDialog()
    End Sub

    Private Sub PauseMovieAndAllTimers()
        mPlayer.Ctlcontrols.pause()
        Timer.Enabled = False
        TimerSub.Enabled = False
    End Sub

    Public Sub LoadSettings()
        delayBefore = My.Computer.Registry.GetValue(AppRegKey, "StartDelay", 0)
        delayAfter = My.Computer.Registry.GetValue(AppRegKey, "EndDelay", 0)
        commonDelay = My.Computer.Registry.GetValue(AppRegKey, "AddDelay", 0)
        stopOnEndOfSub = My.Computer.Registry.GetValue(AppRegKey, "stopOnEndOfSub", True)

        lblStartBefore.Text = delayBefore & " ms"
        lblEndAfter.Text = delayAfter & " ms"
        lblConstantDelay.Text = commonDelay & " ms"

    End Sub

    Private Sub SaveToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SaveToolStripMenuItem.Click
        If Not dgvSubtitles.Rows.Count = 0 Then mySubtitles.save()
    End Sub

    Private Sub PlayToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PlayToolStripMenuItem.Click
        btnPlay_Click(Nothing, Nothing)
    End Sub

    Private Sub ForwardToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ForwardToolStripMenuItem.Click
        btnFF_Click(Nothing, Nothing)
    End Sub

    Private Sub RewindToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RewindToolStripMenuItem.Click
        btnFR_Click(Nothing, Nothing)
    End Sub

    Private Sub volumeUpToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles volumeUpToolStripMenuItem.Click
        sldVolume.Value += 5
    End Sub

    Private Sub volumeDownToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles volumeDownToolStripMenuItem.Click
        sldVolume.Value -= 5
    End Sub

    Private Sub MuteToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MuteToolStripMenuItem.Click
        mPlayer.settings.volume = 0
    End Sub

    Private Sub MaxToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MaxToolStripMenuItem.Click
        mPlayer.settings.volume = 100
    End Sub

    Private Sub playRateUpToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles playRateUpToolStripMenuItem.Click
        mPlayer.settings.rate += 0.25
        lblPlayRate.Text = mPlayer.settings.rate & "x"
    End Sub

    Private Sub playRateDownToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles playRateDownToolStripMenuItem.Click
        mPlayer.settings.rate -= 0.25
        lblPlayRate.Text = mPlayer.settings.rate & "x"
    End Sub

    Private Sub ResetToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ResetToolStripMenuItem.Click
        mPlayer.settings.rate = 1
    End Sub

    Private Sub StartSelectedOnCurrentPositionToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles StartSelectedOnCurrentPositionToolStripMenuItem.Click
        Dim curpos(2) As String
        Dim milisecondsTemp As Short

        If dgvSubtitles.SelectedCells.Count = 0 Then Exit Sub

        curpos = Split(mPlayer.Ctlcontrols.currentPosition, DecimalSeparator, 2)
        Dim secondsTemp As Short = CShort(curpos(0))
        If curpos.Count = 1 Then
            milisecondsTemp = 0
        Else
            milisecondsTemp = CShort(Microsoft.VisualBasic.Left(curpos(1), 3))
        End If

        Dim timeInMS As Integer = secondsTemp * 1000 + milisecondsTemp
        Dim row As Integer = dgvSubtitles.SelectedCells.Item(0).OwningRow.Index

        convertMilisecondsToShowHideCell(timeInMS, row, True)
        dgvSubtitles_SelectionChanged(Nothing, Nothing)
    End Sub

    Private Sub EndSelectedOnCurrentPositionToolStripMenuItem_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles EndSelectedOnCurrentPositionToolStripMenuItem.Click
        Dim curpos(2) As String
        Dim milisecondsTemp As Short

        If dgvSubtitles.SelectedCells.Count = 0 Then Exit Sub

        curpos = Split(mPlayer.Ctlcontrols.currentPosition, DecimalSeparator, 2)
        Dim secondsTemp As Short = CShort(curpos(0))
        If curpos.Count = 1 Then
            milisecondsTemp = 0
        Else
            milisecondsTemp = CShort(Microsoft.VisualBasic.Left(curpos(1), 3))
        End If

        Dim timeInMS As Integer = secondsTemp * 1000 + milisecondsTemp
        Dim row As Integer = dgvSubtitles.SelectedCells.Item(0).OwningRow.Index

        convertMilisecondsToShowHideCell(timeInMS, row, False)
        dgvSubtitles_SelectionChanged(Nothing, Nothing)
    End Sub

    Private Sub OnCurrentMoviePositionToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OnCurrentMoviePositionToolStripMenuItem.Click
        Dim curpos(2) As String
        Dim milisecondsTemp As Short
        Dim tempSub As New Subtitles.SubtitleType

        mPlayer.Ctlcontrols.pause()

        curpos = Split(mPlayer.Ctlcontrols.currentPosition, DecimalSeparator, 2)
        If curpos.Count = 1 Then
            Array.Resize(curpos, 2)
            curpos(1) = "000"
            milisecondsTemp = 0
        Else
            milisecondsTemp = CShort(Microsoft.VisualBasic.Left(curpos(1), 3))
        End If

        Dim timeInMS As Integer = CInt(curpos(0)) * 1000 + milisecondsTemp

        Dim checkTemp As Integer = checkIfNewSubtitleExistsOnGivenTime(timeInMS)
        If checkTemp > 0 Then
            addToDebugList(loadStringFromLangFile("subtitleEntryWord") & " " & checkTemp & ": " & _
                           loadStringFromLangFile("subtitleAlreadyExistsOnGivenTime"))
            ViewTabsToolStripMenuItem.Checked = True
            tabControl.SelectedTab = tabDebug
            ViewTabsToolStripMenuItem_Click(Nothing, Nothing)
            Exit Sub
        End If

        dgvSubtitles.Rows.Add()
        tempSub.ID = dgvSubtitles.RowCount
        tempSub.showTimeInMS = timeInMS
        tempSub.hideTimeInMS = timeInMS + 500
        tempSub.text = ""
        tempSub.isBold = False
        tempSub.isItalic = False
        tempSub.translationText = ""
        mySubtitles.setAll(tempSub.ID - 1, tempSub)

        mySubtitles.passLineToDataGridView(tempSub.ID - 1)

        dgvSubtitles_SelectionChanged(Nothing, Nothing)

        sortDGV()
    End Sub

    Private Sub ApplyCurrentConstantDelayToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ApplyCurrentConstantDelayToolStripMenuItem.Click
        For i = 0 To dgvSubtitles.RowCount - 1
            Dim startTime As Integer = convertShowHideCellToMiliseconds(i, True)
            Dim endTime As Integer = convertShowHideCellToMiliseconds(i, False)

            startTime += commonDelay
            endTime += commonDelay

            convertMilisecondsToShowHideCell(startTime, i, True)
            convertMilisecondsToShowHideCell(endTime, i, False)
        Next
    End Sub

    Private Sub CurFPS23976ToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CurFPS23976ToolStripMenuItem.Click

        CurFPS23976ToolStripMenuItem.Checked = True
        CurFPS25ToolStripMenuItem.Checked = False
        CurFPS15ToolStripMenuItem.Checked = False
        CurFPS20ToolStripMenuItem.Checked = False
        CurFPS24ToolStripMenuItem.Checked = False
        CurFPS2997ToolStripMenuItem.Checked = False
        CurFPS30ToolStripMenuItem.Checked = False
        currentFPS = 23.976

    End Sub

    Private Sub CurFPS25ToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CurFPS25ToolStripMenuItem.Click

        CurFPS23976ToolStripMenuItem.Checked = False
        CurFPS25ToolStripMenuItem.Checked = True
        CurFPS15ToolStripMenuItem.Checked = False
        CurFPS20ToolStripMenuItem.Checked = False
        CurFPS24ToolStripMenuItem.Checked = False
        CurFPS2997ToolStripMenuItem.Checked = False
        CurFPS30ToolStripMenuItem.Checked = False
        currentFPS = 25

    End Sub

    Private Sub ToFPS23976ToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToFPS23976ToolStripMenuItem.Click

        If dgvSubtitles.RowCount = 0 Then Exit Sub

        If currentFPS = 0 Or currentFPS = 23.976 Then
            addToDebugList(loadStringFromLangFile("noFPSsetOrCurrentFPS"))
            Exit Sub
        End If

        ConvertToFPS(23.976)

        CurFPS23976ToolStripMenuItem.PerformClick()

    End Sub

    Private Sub ToFPS25ToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToFPS25ToolStripMenuItem.Click

        If dgvSubtitles.RowCount = 0 Then Exit Sub

        If currentFPS = 0 Or currentFPS = 25 Then
            addToDebugList(loadStringFromLangFile("noFPSsetOrCurrentFPS"))
            Exit Sub
        End If

        ConvertToFPS(25)

        CurFPS25ToolStripMenuItem.PerformClick()

    End Sub

    Private Sub NewToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles NewToolStripMenuItem.Click
        If subtitleFileSaved() = False Then
            Dim response As MsgBoxResult = MsgBox(loadStringFromLangFile("tableNotEmptyNewPrompt"), MsgBoxStyle.Question + MsgBoxStyle.YesNoCancel)
            Select Case response
                Case vbYes
                    mySubtitles.save()
                    dgvSubtitles.Rows.Clear()
                    mySubtitles.clear()
                Case vbNo
                    dgvSubtitles.Rows.Clear()
                    mySubtitles.clear()
                Case vbCancel
                    Exit Sub
            End Select
        End If
    End Sub

    Private Sub CurFPS15ToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CurFPS15ToolStripMenuItem.Click

        CurFPS23976ToolStripMenuItem.Checked = False
        CurFPS25ToolStripMenuItem.Checked = False
        CurFPS15ToolStripMenuItem.Checked = True
        CurFPS20ToolStripMenuItem.Checked = False
        CurFPS24ToolStripMenuItem.Checked = False
        CurFPS2997ToolStripMenuItem.Checked = False
        CurFPS30ToolStripMenuItem.Checked = False
        currentFPS = 15

    End Sub

    Private Sub CurFPS20ToolStripMenuItem_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles CurFPS20ToolStripMenuItem.Click

        CurFPS23976ToolStripMenuItem.Checked = False
        CurFPS25ToolStripMenuItem.Checked = False
        CurFPS15ToolStripMenuItem.Checked = False
        CurFPS20ToolStripMenuItem.Checked = True
        CurFPS24ToolStripMenuItem.Checked = False
        CurFPS2997ToolStripMenuItem.Checked = False
        CurFPS30ToolStripMenuItem.Checked = False
        currentFPS = 20

    End Sub

    Private Sub CurFPS24ToolStripMenuItem_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles CurFPS24ToolStripMenuItem.Click

        CurFPS23976ToolStripMenuItem.Checked = False
        CurFPS25ToolStripMenuItem.Checked = False
        CurFPS15ToolStripMenuItem.Checked = False
        CurFPS20ToolStripMenuItem.Checked = False
        CurFPS24ToolStripMenuItem.Checked = True
        CurFPS2997ToolStripMenuItem.Checked = False
        CurFPS30ToolStripMenuItem.Checked = False
        currentFPS = 24

    End Sub

    Private Sub CurFPS2997ToolStripMenuItem_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles CurFPS2997ToolStripMenuItem.Click

        CurFPS23976ToolStripMenuItem.Checked = False
        CurFPS25ToolStripMenuItem.Checked = False
        CurFPS15ToolStripMenuItem.Checked = False
        CurFPS20ToolStripMenuItem.Checked = False
        CurFPS24ToolStripMenuItem.Checked = False
        CurFPS2997ToolStripMenuItem.Checked = True
        CurFPS30ToolStripMenuItem.Checked = False
        currentFPS = 29.97

    End Sub

    Private Sub CurFPS30ToolStripMenuItem_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles CurFPS30ToolStripMenuItem.Click

        CurFPS23976ToolStripMenuItem.Checked = False
        CurFPS25ToolStripMenuItem.Checked = False
        CurFPS15ToolStripMenuItem.Checked = False
        CurFPS20ToolStripMenuItem.Checked = False
        CurFPS24ToolStripMenuItem.Checked = False
        CurFPS2997ToolStripMenuItem.Checked = False
        CurFPS30ToolStripMenuItem.Checked = True
        currentFPS = 30

    End Sub

    Private Sub ToFPS15ToolStripMenuItem_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles ToFPS15ToolStripMenuItem.Click

        If dgvSubtitles.RowCount = 0 Then Exit Sub

        If currentFPS = 0 Or currentFPS = 15 Then
            addToDebugList(loadStringFromLangFile("noFPSsetOrCurrentFPS"))
            Exit Sub
        End If

        ConvertToFPS(15)

        CurFPS15ToolStripMenuItem.PerformClick()

    End Sub

    Private Sub ToFPS20ToolStripMenuItem_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles ToFPS20ToolStripMenuItem.Click

        If dgvSubtitles.RowCount = 0 Then Exit Sub

        If currentFPS = 0 Or currentFPS = 20 Then
            addToDebugList(loadStringFromLangFile("noFPSsetOrCurrentFPS"))
            Exit Sub
        End If

        ConvertToFPS(20)

        CurFPS20ToolStripMenuItem.PerformClick()

    End Sub

    Private Sub ToFPS24ToolStripMenuItem_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles ToFPS24ToolStripMenuItem.Click

        If dgvSubtitles.RowCount = 0 Then Exit Sub

        If currentFPS = 0 Or currentFPS = 24 Then
            addToDebugList(loadStringFromLangFile("noFPSsetOrCurrentFPS"))
            Exit Sub
        End If

        ConvertToFPS(24)

        CurFPS24ToolStripMenuItem.PerformClick()

    End Sub

    Private Sub toFPS2997ToolStripMenuItem_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles toFPS2997ToolStripMenuItem.Click

        If dgvSubtitles.RowCount = 0 Then Exit Sub

        If currentFPS = 0 Or currentFPS = 29.97 Then
            addToDebugList(loadStringFromLangFile("noFPSsetOrCurrentFPS"))
            Exit Sub
        End If

        ConvertToFPS(29.97)

        CurFPS2997ToolStripMenuItem.PerformClick()

    End Sub

    Private Sub ToFPS30ToolStripMenuItem_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles ToFPS30ToolStripMenuItem.Click

        If dgvSubtitles.RowCount = 0 Then Exit Sub

        If currentFPS = 0 Or currentFPS = 30 Then
            addToDebugList(loadStringFromLangFile("noFPSsetOrCurrentFPS"))
            Exit Sub
        End If

        ConvertToFPS(30)

        CurFPS30ToolStripMenuItem.PerformClick()

    End Sub

    Private Sub CheckForOverlappingSubtitles(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CheckForOverlappingSubtitlesToolStripMenuItem.Click

        If dgvSubtitles.RowCount = 0 Then Exit Sub

        addToDebugList(loadStringFromLangFile("startingCheckForOverlaps"))
        Dim startTime As Integer
        Dim endTime As Integer
        Dim problemsCount As Integer = 0

        For i = 0 To dgvSubtitles.RowCount - 1
            startTime = convertShowHideCellToMiliseconds(i, True)
            endTime = convertShowHideCellToMiliseconds(i, False)

            If endTime <= startTime Then
                addToDebugList(loadStringFromLangFile("subtitleEntryWord") & " " & getSubtitleID(i) & ":" & " " & _
                               loadStringFromLangFile("hideTimeLessOrEqual"))
                problemsCount += 1
            End If

            If Not i = dgvSubtitles.RowCount - 1 Then
                startTime = convertShowHideCellToMiliseconds(i + 1, True)

                If startTime < endTime Then
                    addToDebugList(loadStringFromLangFile("subtitleEntryWord") & " " & getSubtitleID(i) & ":" & " " & _
                                   loadStringFromLangFile("nextLineStartsBeforePreviousEnds"))
                    problemsCount += 1
                End If
            End If
        Next

        If problemsCount = 0 Then
            addToDebugList(loadStringFromLangFile("allTimingsCorrect"))
        Else
            addToDebugList(loadStringFromLangFile("checkEnded") & " " & problemsCount & " " & _
                           loadStringFromLangFile("soManyProblemsFound"))
            ViewTabsToolStripMenuItem.Checked = True
            tabControl.SelectedTab = tabDebug
            ViewTabsToolStripMenuItem_Click(Nothing, Nothing)
        End If

    End Sub

    Private Sub AboutToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AboutToolStripMenuItem.Click
        frmAbout.ShowDialog()
    End Sub

    Private Sub ApplyCustomDelayToolStripMenuItem_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles ApplyCustomDelayToolStripMenuItem.Click
        Dim delay, percentComplete As Integer
        Try
            delay = InputBox(loadStringFromLangFile("addCustomDelayPrompt"), , "0")
        Catch
            Exit Sub
        End Try

        For i = 0 To dgvSubtitles.RowCount - 1
            Dim startTime As Integer = convertShowHideCellToMiliseconds(i, True)
            Dim endTime As Integer = convertShowHideCellToMiliseconds(i, False)

            startTime += delay
            endTime += delay

            convertMilisecondsToShowHideCell(startTime, i, True)
            convertMilisecondsToShowHideCell(endTime, i, False)

            percentComplete = i / dgvSubtitles.RowCount

            statusStrip.Text = percentComplete.ToString + "% completed, please wait..."
            Me.Invalidate()
        Next

    End Sub

    Private Sub GreekToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles GreekToolStripMenuItem.Click
        My.Computer.Registry.SetValue(AppRegKey, "LanguageFile", Application.StartupPath & "\Languages\Greek.sel")
        loadTranslation(1)
    End Sub

    Private Sub nudShow_upDownButtonClick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles nudShow.UpButtonClick, nudShow.DownButtonClick
        If dgvSubtitles.SelectedCells.Count > 0 Then
            mtbShow.Text = convertMilisecondsToShowHideCell(nudShow.Value)
        End If
    End Sub

    Private Sub nudHide_UpDownButtonClick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles nudHide.UpButtonClick, nudHide.DownButtonClick
        If dgvSubtitles.SelectedCells.Count > 0 Then
            mtbHide.Text = convertMilisecondsToShowHideCell(nudHide.Value)
        End If
    End Sub

    Private Sub nudDuration_UpDownButtonClick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles nudDuration.UpButtonClick, nudDuration.DownButtonClick
        If dgvSubtitles.SelectedCells.Count > 0 Then
            mtbDuration.Text = convertMilisecondsToShowHideCell(nudDuration.Value)
        End If
    End Sub

    Private Sub mtbShow_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles mtbShow.TextChanged

        If dgvSubtitles.SelectedCells.Count > 0 Then
            dgvSubtitles.SelectedCells(0).OwningRow.Cells("subShow").Value = mtbShow.Text
            mySubtitles.setShowTime(dgvSubtitles.SelectedCells(0).OwningRow.Index, mtbShow.Text)
            If rbtLockShow.Checked Or rbtLockHide.Checked Then
                checkIfHideLessThanShow("Show")
                calculateDuration()
            ElseIf rbtLockDuration.Checked Then
                nudHide.Value = nudShow.Value + nudDuration.Value
            End If
        End If

    End Sub

    Private Sub mtbHide_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles mtbHide.TextChanged
        If dgvSubtitles.SelectedCells.Count > 0 Then
            dgvSubtitles.SelectedCells(0).OwningRow.Cells("subHide").Value = mtbHide.Text
            mySubtitles.setHideTime(dgvSubtitles.SelectedCells(0).OwningRow.Index, mtbHide.Text)
            If rbtLockShow.Checked Or rbtLockHide.Checked Then
                checkIfHideLessThanShow("Hide")
                calculateDuration()
            ElseIf rbtLockDuration.Checked Then
                nudShow.Value = nudHide.Value - nudDuration.Value
            End If
        End If
    End Sub

    Private Sub mtbDuration_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles mtbDuration.TextChanged
        If dgvSubtitles.SelectedCells.Count > 0 Then
            If rbtLockShow.Checked Then
                nudHide.Value = nudShow.Value + nudDuration.Value
            ElseIf rbtLockHide.Checked Then
                nudShow.Value = nudHide.Value - nudDuration.Value
            Else
                nudHide.Value = nudShow.Value + nudDuration.Value
            End If
            nudHide_UpDownButtonClick(Nothing, Nothing)
        End If
    End Sub

    Private Sub calculateDuration()
        nudDuration.Value = nudHide.Value - nudShow.Value
        mtbDuration.Text = convertMilisecondsToShowHideCell(nudDuration.Value)
    End Sub

    Private Sub rtbSubtitle_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles rtbSubtitle.TextChanged

        If mPlayer.playState = WMPLib.WMPPlayState.wmppsPlaying Then Exit Sub
        Dim temp2 As String = ""

        If dgvSubtitles.SelectedCells.Count > 0 Then
            If Not rtbSubtitle.Text = "" Then
                For Each temp3 As String In rtbSubtitle.Lines
                    temp2 = temp2 & temp3 & " | "
                Next
                temp2 = Microsoft.VisualBasic.Left(temp2, temp2.Length - 3)
            End If
            mySubtitles.setText(dgvSubtitles.SelectedCells(0).OwningRow.Index, temp2)
            mySubtitles.passLineToDataGridView(dgvSubtitles.SelectedCells(0).OwningRow.Index)
        End If

    End Sub

    Public Sub tmrDebug_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tmrDebug.Tick
        Select Case tick
            Case 0
                lblStatus.Text = lstDebug.Items(0).ToString
            Case 30
                If incompleteLanguageFile = False Then
                    lblStatus.Text = loadStringFromLangFile("readyStatus")
                End If
                tmrDebug.Enabled = False
        End Select
        tick += 1
    End Sub

    Private Sub dgvSubtitles_RowsRemoved(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewRowsRemovedEventArgs) Handles dgvSubtitles.RowsRemoved
        findSubForCurrentTime()
        dgvSubtitles_SelectionChanged(Nothing, Nothing)
    End Sub

    Private Sub mPlayer_OpenStateChange(ByVal sender As Object, ByVal e As AxWMPLib._WMPOCXEvents_OpenStateChangeEvent) Handles mPlayer.OpenStateChange
        If mPlayer.openState = WMPLib.WMPOpenState.wmposMediaOpen Then
            sldPosition.Maximum = mPlayer.currentMedia.duration
            mPlayer.Ctlcontrols.pause()
        End If
    End Sub

    Private Sub mPlayer_PlayStateChange(ByVal sender As Object, ByVal e As AxWMPLib._WMPOCXEvents_PlayStateChangeEvent) Handles mPlayer.PlayStateChange
        If mPlayer.playState = WMPLib.WMPPlayState.wmppsStopped Then
            lblShowSub.Visible = False
            btnPlay.BackgroundImage = My.Resources.play
        ElseIf mPlayer.playState = WMPLib.WMPPlayState.wmppsPlaying Then
            btnPlay.BackgroundImage = My.Resources.pause
        Else
            mPlayer.Ctlcontrols.pause()
            btnPlay.BackgroundImage = My.Resources.play
        End If
        'Debug.Print(mPlayer.playState)
    End Sub

    Private Sub chkBold_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chkBold.CheckedChanged
        If Not dgvSubtitles.SelectedCells.Count = 0 Then
            mySubtitles.setIsBold(dgvSubtitles.SelectedCells(0).OwningRow.Index, chkBold.Checked)
            dgvSubtitles_SelectionChanged(Nothing, Nothing)
        Else
            chkBold.Checked = False
        End If
    End Sub

    Private Sub chkItalic_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles chkItalic.CheckedChanged
        If Not dgvSubtitles.SelectedCells.Count = 0 Then
            mySubtitles.setIsItalic(dgvSubtitles.SelectedCells(0).OwningRow.Index, chkItalic.Checked)
            dgvSubtitles_SelectionChanged(Nothing, Nothing)
        Else
            chkItalic.Checked = False
        End If
    End Sub


    Public Sub formatSubtitle()
        formatSubtitle(currentRow)
    End Sub

    Public Sub formatSubtitle(ByVal row As Integer)
        Dim tempProperties(2) As String
        tempProperties = Split(mySubtitles.getPropertiesString(row), ",")
        Select Case tempProperties(0)
            Case "BI"
                rtbSubtitle.Font = New Font(rtbSubtitle.Font, FontStyle.Bold + FontStyle.Italic)
                lblShowSub.Font = New Font(lblShowSub.Font, FontStyle.Bold + FontStyle.Italic)
            Case "B"
                rtbSubtitle.Font = New Font(rtbSubtitle.Font, FontStyle.Bold)
                lblShowSub.Font = New Font(lblShowSub.Font, FontStyle.Bold)
            Case "I"
                rtbSubtitle.Font = New Font(rtbSubtitle.Font, FontStyle.Italic)
                lblShowSub.Font = New Font(lblShowSub.Font, FontStyle.Italic)
            Case ""
                rtbSubtitle.Font = New Font(rtbSubtitle.Font, FontStyle.Regular)
                lblShowSub.Font = New Font(lblShowSub.Font, FontStyle.Regular)
        End Select
        mySubtitles.convertPropertiesStringToProperties(row)
    End Sub

    Private Sub updateSubtitleProperties()
        Dim tempProperties(2) As String
        Dim currentRow As Integer = dgvSubtitles.SelectedCells(0).OwningRow.Index

        tempProperties = Split(mySubtitles.getPropertiesString(currentRow), ",")
        If chkBold.Checked = True Then
            If chkItalic.Checked = True Then
                tempProperties(0) = "BI"
            Else
                tempProperties(0) = "B"
            End If
        Else
            If chkItalic.Checked = True Then
                tempProperties(0) = "I"
            Else
                tempProperties(0) = ""
            End If
        End If
        If tempProperties.Length = 1 Then
            mySubtitles.setPropertiesString(currentRow, tempProperties(0))
        Else
            mySubtitles.setPropertiesString(currentRow, tempProperties(0) & "," & tempProperties(1))
        End If
        mySubtitles.convertPropertiesStringToProperties(currentRow)
        mySubtitles.passLineToDataGridView(currentRow)
    End Sub

    Private Sub updateSubtitlePropertiesInDB()
        Dim tempProperties(2) As String
        tempProperties(1) = ""
        tempProperties = Split(dgvSubtitles.SelectedCells(0).OwningRow.Cells("subProperties").Value, ",")
        'If chkBold.Checked = True Then 
        If tempProperties(1) = "" Then
            dgvSubtitles.SelectedCells(0).OwningRow.Cells("subProperties").Value = tempProperties(0)
        Else
            dgvSubtitles.SelectedCells(0).OwningRow.Cells("subProperties").Value = tempProperties(0) & "," & tempProperties(1)
        End If
    End Sub

    Private Sub SortSubtitlesBasedOnShowTimingToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SortSubtitlesBasedOnShowTimingToolStripMenuItem.Click
        sortDGV()
        mySubtitles.passDataGridViewToArray()
    End Sub

    Public Sub scrollToSelectedRow()
        Dim halfWay As Integer = (dgvSubtitles.DisplayedRowCount(False) / 2)
        If dgvSubtitles.FirstDisplayedScrollingRowIndex + halfWay > dgvSubtitles.SelectedRows(0).Index Or (dgvSubtitles.FirstDisplayedScrollingRowIndex + dgvSubtitles.DisplayedRowCount(False) - halfWay) <= dgvSubtitles.SelectedRows(0).Index Then

            Dim targetRow As Integer = dgvSubtitles.SelectedRows(0).Index

            targetRow = Math.Max(targetRow - halfWay, 0)
            dgvSubtitles.FirstDisplayedScrollingRowIndex = targetRow

        End If
    End Sub

    Private Sub btnPlay_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPlay.Click
        If Not mPlayer.URL = "" Then
            If mPlayer.playState = WMPLib.WMPPlayState.wmppsPlaying Then
                mPlayer.Ctlcontrols.pause()
                btnPlay.BackgroundImage = My.Resources.play
            Else
                playMovie()
                btnPlay.BackgroundImage = My.Resources.pause
            End If
        End If
    End Sub

    Private Sub btnFR_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnFR.Click
        If Not cmbFRorFFby.Text = "" And Not mPlayer.URL = "" Then
            Dim temp() As String = Split(cmbFRorFFby.Text, " ms")
            TimerSub.Enabled = False
            mPlayer.Ctlcontrols.currentPosition -= CInt(temp(0)) / 1000
            If Not dgvSubtitles.RowCount = 0 Then
                findSubForCurrentTime()
            End If
            If mPlayer.playState = WMPLib.WMPPlayState.wmppsPlaying Then
                TimerSub.Enabled = True
            Else
                updateCurrentPositionLabel()
            End If
        End If
    End Sub

    Private Sub btnFF_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnFF.Click
        If Not cmbFRorFFby.Text = "" And Not mPlayer.URL = "" Then
            Dim temp() As String = Split(cmbFRorFFby.Text, " ms")
            TimerSub.Enabled = False
            mPlayer.Ctlcontrols.currentPosition += (CDbl(temp(0)) / 1000)
            If Not dgvSubtitles.RowCount = 0 Then
                findSubForCurrentTime()
            End If
            If mPlayer.playState = WMPLib.WMPPlayState.wmppsPlaying Then
                TimerSub.Enabled = True
            Else
                updateCurrentPositionLabel()
            End If
        End If
    End Sub

    Private Sub btnToStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        TimerSub.Enabled = False
        mPlayer.Ctlcontrols.currentPosition = 0
        If Not dgvSubtitles.RowCount = 0 Then
            findSubForCurrentTime()
        End If
        TimerSub.Enabled = True
    End Sub

    Private Sub btnToEnd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        mPlayer.Ctlcontrols.currentPosition = mPlayer.currentMedia.duration
    End Sub

    Private Sub cmbFRorFFby_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles cmbFRorFFby.KeyPress
        If Char.IsNumber(e.KeyChar) = False Then
            e.Handled = True
        End If
    End Sub

    Private Sub sldVolume_Scroll(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles sldVolume.Scroll
        mPlayer.settings.volume = sldVolume.Value
        toolTip.SetToolTip(sldVolume, sldVolume.Value)
    End Sub

    Public Sub updateCurrentPositionLabel()
        Dim curpos(1) As String
        Dim curposint As Integer
        curpos = Split(mPlayer.Ctlcontrols.currentPosition, DecimalSeparator, 2)
        If curpos.Count = 2 Then
            curpos(1) = Microsoft.VisualBasic.Left(curpos(1), 3)
            If curpos(1).Length = 2 Then
                curpos(1) = curpos(1) & "0"
            ElseIf curpos(1).Length = 1 Then
                curpos(1) = curpos(1) & "00"
            End If
            curposint = CInt(curpos(0)) * 1000 + CInt(curpos(1))
            lblCurPos.Text = convertMilisecondsToShowHideCell(curposint)
        Else
            curposint = CInt(curpos(0)) * 1000
            lblCurPos.Text = convertMilisecondsToShowHideCell(curposint)
        End If
        If sldPosition.Maximum = 0 Then sldPosition.Maximum = mPlayer.currentMedia.duration
        sldPosition.Value = mPlayer.Ctlcontrols.currentPosition
    End Sub

    Private Sub sldPosition_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles sldPosition.MouseDown
        If mPlayer.playState = WMPLib.WMPPlayState.wmppsPlaying Then
            mPlayer.Ctlcontrols.pause()
            wasPaused = False
        Else
            wasPaused = True
        End If
    End Sub

    Private Sub sldPosition_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles sldPosition.MouseUp
        If mPlayer.playState = WMPLib.WMPPlayState.wmppsPaused And wasPaused = False Then
            mPlayer.Ctlcontrols.play()
        End If
    End Sub

    Private Sub sldPosition_Scroll(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles sldPosition.Scroll
        mPlayer.Ctlcontrols.currentPosition = sldPosition.Value
    End Sub

    Private Sub CopyToClipboardToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Clipboard.SetText(lstDebug.SelectedItem)
    End Sub

    Private Sub tabDebug_Enter(ByVal sender As Object, ByVal e As System.EventArgs) Handles tabDebug.Enter
        tabDebug.ImageIndex = -1
    End Sub

    Public Sub ViewTabsToolStripMenuItem_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles ViewTabsToolStripMenuItem.Click
        If ViewTabsToolStripMenuItem.Checked = True Then
            'If mPlayer.URL = "" Then
            'MessageBox.Show("No video is loaded")
            'ViewTabsToolStripMenuItem.Checked = False
            'Else
            tabControl.Visible = True
            'End If
        Else
            tabControl.Visible = False
        End If
    End Sub

    Private Sub checkIfHideLessThanShow(ByVal sender As String)
        If nudHide.Value - nudShow.Value < 0 Then
            If rbtLockShow.Checked = True Then
                nudHide.Value = nudShow.Value
                nudHide_UpDownButtonClick(Nothing, Nothing)
            ElseIf rbtLockHide.Checked = True Then
                nudShow.Value = nudHide.Value
                nudShow_upDownButtonClick(Nothing, Nothing)
            Else
                If sender = "Show" Then
                    nudHide.Value = nudShow.Value
                    nudHide_UpDownButtonClick(Nothing, Nothing)
                ElseIf sender = "Hide" Then
                    nudShow.Value = nudHide.Value
                    nudShow_upDownButtonClick(Nothing, Nothing)
                End If
            End If
        End If
    End Sub

    Private Sub btnQuickAdd_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles btnQuickAdd.MouseDown
        If mPlayer.URL = "" Then Exit Sub

        Dim curpos(2) As String
        Dim milisecondsTemp As Short

        editMode = True

        curpos = Split(mPlayer.Ctlcontrols.currentPosition, DecimalSeparator, 2)
        If curpos.Count = 1 Then
            Array.Resize(curpos, 2)
            curpos(1) = "000"
            milisecondsTemp = 0
        Else
            milisecondsTemp = CShort(Microsoft.VisualBasic.Left(curpos(1), 3))
        End If

        Dim timeInMS As Integer = CInt(curpos(0)) * 1000 + milisecondsTemp

        Dim checkTemp As Integer = checkIfNewSubtitleExistsOnGivenTime(timeInMS)
        If checkTemp > 0 Then
            addToDebugList(loadStringFromLangFile("subtitleEntryWord") & " " & checkTemp & ": " & _
                           loadStringFromLangFile("subtitleAlreadyExistsOnGivenTime"))
            ViewTabsToolStripMenuItem.Checked = True
            tabControl.SelectedTab = tabDebug
            ViewTabsToolStripMenuItem_Click(Nothing, Nothing)
            Exit Sub
        End If

        tempSub.ID = dgvSubtitles.RowCount
        'If dgvSubtitles.AllowUserToAddRows Then tempSub.ID = dgvSubtitles.RowCount - 1
        tempSub.showTimeInMS = timeInMS
        tempSub.text = ""
        tempSub.isBold = False
        tempSub.isItalic = False
        tempSub.translationText = ""
    End Sub

    Private Sub btnQuickAdd_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles btnQuickAdd.MouseUp
        If mPlayer.URL = "" Then Exit Sub

        Dim curpos(2) As String
        Dim milisecondsTemp As Short

        If chkPauseAfterQuick.Checked = True Then
            mPlayer.Ctlcontrols.pause()
        End If

        curpos = Split(mPlayer.Ctlcontrols.currentPosition, DecimalSeparator, 2)
        If curpos.Count = 1 Then
            Array.Resize(curpos, 2)
            curpos(1) = "000"
            milisecondsTemp = 0
        Else
            milisecondsTemp = CShort(Microsoft.VisualBasic.Left(curpos(1), 3))
        End If

        Dim timeInMS As Integer = CInt(curpos(0)) * 1000 + milisecondsTemp

        tempSub.hideTimeInMS = timeInMS
        mySubtitles.setAll(tempSub.ID, tempSub)

        mySubtitles.addNewLineToDataGridView(tempSub.ID)

        dgvSubtitles_SelectionChanged(Nothing, Nothing)

        sortDGV()

        If Not lstDebug.Items.Item(0) = loadStringFromLangFile("pleaseCheckForOverlaps") Then
            addToDebugList(loadStringFromLangFile("pleaseCheckForOverlaps"))
        End If

        editMode = False
    End Sub

    Private Sub btnQuickEdit_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles btnQuickEdit.MouseDown
        If mPlayer.URL = "" Then Exit Sub

        Dim curpos(2) As String
        Dim milisecondsTemp As Short

        editMode = True

        If dgvSubtitles.SelectedCells.Count = 0 Then Exit Sub

        curpos = Split(mPlayer.Ctlcontrols.currentPosition, DecimalSeparator, 2)
        Dim secondsTemp As Short = CShort(curpos(0))
        If curpos.Count = 1 Then
            milisecondsTemp = 0
        Else
            milisecondsTemp = CShort(Microsoft.VisualBasic.Left(curpos(1), 3))
        End If

        Dim timeInMS As Integer = secondsTemp * 1000 + milisecondsTemp
        Dim row As Integer = dgvSubtitles.SelectedCells.Item(0).OwningRow.Index

        convertMilisecondsToShowHideCell(timeInMS, row, True)
        dgvSubtitles_SelectionChanged(Nothing, Nothing)
    End Sub

    Private Sub btnQuickEdit_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles btnQuickEdit.MouseUp
        If mPlayer.URL = "" Then Exit Sub

        Dim curpos(2) As String
        Dim milisecondsTemp As Short

        If dgvSubtitles.SelectedCells.Count = 0 Then Exit Sub

        curpos = Split(mPlayer.Ctlcontrols.currentPosition, DecimalSeparator, 2)
        Dim secondsTemp As Short = CShort(curpos(0))
        If curpos.Count = 1 Then
            milisecondsTemp = 0
        Else
            milisecondsTemp = CShort(Microsoft.VisualBasic.Left(curpos(1), 3))
        End If

        Dim timeInMS As Integer = secondsTemp * 1000 + milisecondsTemp
        Dim row As Integer = dgvSubtitles.SelectedCells.Item(0).OwningRow.Index

        convertMilisecondsToShowHideCell(timeInMS, row, False)
        dgvSubtitles_SelectionChanged(Nothing, Nothing)

        If Not lstDebug.Items.Item(0) = loadStringFromLangFile("pleaseCheckForOverlaps") Then
            addToDebugList(loadStringFromLangFile("pleaseCheckForOverlaps"))
        End If

        editMode = False
    End Sub

    Private Sub stopMovie()
        mPlayer.Ctlcontrols.stop()
        TimerSub.Enabled = False
        lblShowSub.Text = ""
        pnlTimerOnly.Visible = True
        oldRow = -1
    End Sub

    Private Sub playMovie()
        mPlayer.Ctlcontrols.currentPosition = convertShowHideCellToMiliseconds(lblCurPos.Text) / 1000
        mPlayer.Ctlcontrols.play()
        sldPosition.Maximum = mPlayer.currentMedia.duration
        editMode = False
        lblPlayRate.Text = mPlayer.settings.rate & "x"
        findSubForCurrentTime()
        TimerSub.Enabled = True
    End Sub

    Sub ReformatInvalidString(ByRef str As String)
        If str = Nothing Then str = New String("00:00:00,000")
        str.Trim()
        If str = String.Empty Or str.Length <= 10 Then
            str = "00:00:00,000"
        End If
    End Sub


    Friend Sub dgvSubtitles_SelectionChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles dgvSubtitles.SelectionChanged
        If dgvSubtitles.SelectedRows.Count > 0 Then
            'Is there a subtitle entry for this row
            'If Subtitles.SubtitleType.
            nudDuration.Enabled = True
            nudHide.Enabled = True
            nudShow.Enabled = True
            mtbHide.Enabled = True
            mtbShow.Enabled = True
            mtbDuration.Enabled = True
            btnQuickEdit.Enabled = True

            Dim rowNumber As Integer = dgvSubtitles.SelectedCells(0).OwningRow.Index

            ReformatInvalidString(dgvSubtitles.Rows.Item(rowNumber).Cells.Item(1).Value)
            ReformatInvalidString(dgvSubtitles.Rows.Item(rowNumber).Cells.Item(2).Value)

            nudShow.Value = convertShowHideCellToMiliseconds(rowNumber, True)
            nudHide.Value = convertShowHideCellToMiliseconds(rowNumber, False)
            calculateDuration()
            nudShow_upDownButtonClick(Nothing, Nothing)
            nudHide_UpDownButtonClick(Nothing, Nothing)
            rtbSubtitle.Lines = convertMultiLineTextToArray(dgvSubtitles.SelectedCells(0).OwningRow.Cells(3).Value)
            chkBold.Checked = mySubtitles.getIsBold(rowNumber)
            chkItalic.Checked = mySubtitles.getIsItalic(rowNumber)
            updateSubtitleProperties()
            formatSubtitle(rowNumber)
        Else
            nudDuration.Enabled = False
            nudHide.Enabled = False
            nudShow.Enabled = False
            mtbHide.Enabled = False
            mtbShow.Enabled = False
            mtbDuration.Enabled = False
            mtbHide.Text = "__:__:__.___"
            mtbShow.Text = "__:__:__.___"
            mtbDuration.Text = "__:__:__.___"
            btnQuickEdit.Enabled = False
        End If
    End Sub

    Private Sub dgvSubtitles_RowsAdded(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewRowsAddedEventArgs) Handles dgvSubtitles.RowsAdded
        'Dim tempSub As New Subtitles.SubtitleType
        'tempSub.ID = dgvSubtitles.RowCount
        'tempSub.showTimeInMS = 0
        'tempSub.hideTimeInMS = 0
        'tempSub.text = ""
        'tempSub.isBold = False
        'tempSub.isItalic = False
        'tempSub.translationText = ""

        'mySubtitles.setAll(tempSub.ID - 1, tempSub)

        'ReformatInvalidString(dgvSubtitles.Rows(e.RowIndex).Cells(1).Value())
        'ReformatInvalidString(dgvSubtitles.Rows(e.RowIndex).Cells(2).Value())
    End Sub


    '**** Incomplete ****
    Private Function subtitleFileSaved() As Boolean
        Dim result As Boolean = False

        If dgvSubtitles.RowCount > 0 Then
            If String.IsNullOrEmpty(dgvSubtitles.Rows.Item(0).Cells.Item(3).Value) Then
                result = True
            End If
        Else
            result = True
        End If

        Return result
    End Function

    Private Sub btnQuickEdit_MouseHover(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnQuickEdit.MouseHover
        'dgvSubtitles.CurrentRow.DataGridView.BackgroundColor = System.Drawing.Color.Aqua

        dgvSubtitles.SelectedRows(0).Cells(1).Selected = True
        'dgvSubtitles.SelectedRows(0).Cells(2).DataGridView.BackgroundColor = Color.Aqua
    End Sub

    Private Sub OnNextLineToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OnNextLineToolStripMenuItem.Click
        Dim tempSub As New Subtitles.SubtitleType
        tempSub.ID = dgvSubtitles.RowCount + 1
        tempSub.showTimeInMS = 0
        tempSub.hideTimeInMS = 0
        tempSub.text = ""
        tempSub.isBold = False
        tempSub.isItalic = False
        tempSub.translationText = ""

        mySubtitles.setAll(tempSub.ID - 1, tempSub)
        dgvSubtitles.Rows.Add()
    End Sub

    Private Sub btnShowHidePanel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnShowHidePanel.Click
        If SplitContainer1.Panel1Collapsed = True Then
            SplitContainer1.Panel1Collapsed = False
            btnShowHidePanel.BackgroundImage = My.Resources.leftarrow
        Else
            SplitContainer1.Panel1Collapsed = True
            btnShowHidePanel.BackgroundImage = My.Resources.rightarrow
        End If
        rtbSubtitle.Left = chkBold.Right + 10
    End Sub

    Public Function getFirstDebugListItem() As String
        Return lstDebug.Items(0).ToString
    End Function

End Class
